package com.ynkbny.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ynkbny.base.PageResult;
import com.ynkbny.domain.User;
import com.ynkbny.mapper.UserMapper;
import com.ynkbny.service.impl.RouterServiceImpl;
import com.ynkbny.service.impl.UserServiceImpl;
import com.ynkbny.util.Res;
import com.ynkbny.util.UserRoleUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;

/**
 * @author zelin.wang
 * @description 用户登录
 * @date 8/14/2023
 */
@Api(tags = "用户登录登出接口")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserServiceImpl userService;
    @Resource
    RouterServiceImpl routerService;

    @ApiOperation("登出接口")
    @PostMapping("/logout")
    public Res logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Res.ok("登出成功!");
    }
    @ApiOperation("获取当前登录的用户信息")
    @PostMapping("/getUser")
    public Res getUser(){
        Subject subject = SecurityUtils.getSubject();
        String userName = (String) subject.getPrincipal();
        return Res.ok(userService.getBaseMapper().selectOne(new QueryWrapper<User>().lambda().eq(User::getUserName,userName)));
    }

    @ApiOperation("根据用户获取相应菜单")
    @PostMapping("/getRouterByUser")
    public Res getRoles(){
        Subject subject = SecurityUtils.getSubject();
        String userName = (String) subject.getPrincipal();
        return Res.ok(routerService.getRouterByRoleId(userService.getBaseMapper().selectOne(new QueryWrapper<User>().lambda().eq(User::getUserName,userName)).getRoleId()));
    }


    @ApiOperation("登录接口")
    @PostMapping("/login")
    public Res login(@RequestBody User user) {
        //String token = "xxxxxxxx";

        //获取主题对象
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(user.getUserName(),user.getPassword()));
            // 获取当前登录用户的Session
            Session session = SecurityUtils.getSubject().getSession();
            String username= (String) subject.getPrincipal();
            User user1=userService.getOne(new QueryWrapper<User>().eq("user_name",username));
            if (session != null) {
                // 将用户信息存储到Session中
                session.setAttribute("user", user1);
            }
            return Res.ok("登录成功!!");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户错误！！！");
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码错误！！！");
        }
        return Res.fail("请检查用户名和密码！！");
    }

    @ApiOperation("用户添加接口")
    @PostMapping("/add")
    public Res addUser(@RequestBody User user){
        return userService.addUser(user)?Res.ok("添加用户成功！"):Res.fail("添加用户失败，此账号已存在！");
    }

    @ApiOperation("用户修改接口")
    @PostMapping("/edit")
    public Res editUser(@RequestBody User user){
        return userService.editUser(user)?Res.ok("修改用户成功！"):Res.fail("修改用户失败，此账号已存在！");
    }

    @ApiOperation("用户删除接口")
    @DeleteMapping("/delUser")
    public Res delUser(@RequestBody User user) {
        return userService.deleteUser(user)?Res.ok("删除成功！"):Res.fail("删除失败");
    }

    @ApiOperation("用户信息分页查询")
    @PostMapping("/pageList")
    public Res<PageResult<User>> pageList(@RequestParam(name = "pageNum", required = false, defaultValue = "1") int pageNum,
                                          @RequestParam(name = "pageSize", required = false, defaultValue = "15") int pageSize,
                                          @RequestParam(name = "condition", required = false) String conditionJson) {
        return Res.ok(userService.pageList(conditionJson, pageNum, pageSize));
    }

    @ApiOperation("批量添加用户")
    @PostMapping("/addList")
    public Res addList(@RequestBody List<User> users) {
        return Res.ok(userService.saveList(users));
    }
}
